package dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import dao.AccountDao;
import po.Account;
import util.DBUtil;
import util.UUIDUtil;

public class AccountDaoImpl implements AccountDao {

	@Override
	public Account login(String username, String password) {
		Connection con = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		Account account = null;
		try {
			con = DBUtil.getConnection();
			String sql = "select * from account where username = ? and password = ?";
			pst = con.prepareStatement(sql);
			pst.setString(1, username);
			pst.setString(2, password);
			rs = pst.executeQuery();
			while (rs.next()) {
				account = new Account();
				account.setAid(rs.getString("aid"));
				account.setUsername(rs.getString("username"));
				account.setPassword(rs.getString("password"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(con, pst, rs);
		}
		return account;
	}

	@Override
	public Boolean checkUsername(String username) {
		Connection con = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		boolean flag = false;
		try {
			con = DBUtil.getConnection();
			String sql = "select * from account where username = ?";
			pst = con.prepareStatement(sql);
			pst.setString(1, username);
			rs = pst.executeQuery();
			while (rs.next()) {
				flag = true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(con, pst, rs);
		}
		return flag;
	}

	@Override
	public Integer addAccount(Account account) {
		Connection con = null;
		PreparedStatement pst = null;
		int count = 0;
		
		try {
			con = DBUtil.getConnection();
			con.setAutoCommit(false);
			String sql = "insert into account values(account_seq.nextval,?,?,?)";
			pst = con.prepareStatement(sql);
			pst.setString(1, account.getAid());
			pst.setString(2, account.getUsername());
			pst.setString(3,account.getPassword());
			count = pst.executeUpdate();
			con.commit();
		} catch (SQLException e) {
			try {
				con.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		} finally {
			DBUtil.close(con, pst, null);
		}
		return count;
	}
}
